import React, { Component } from 'react'
import { connect } from 'react-redux'
// 这是让页面能够使用 actions
import { bindActionCreators } from 'redux'
// 引入所有的 action
import * as productActions from '../store/actions/product.action'
import * as cartActions from '../store/actions/cart.actions'

class Product extends Component {
	componentDidMount() {
		let { loadProducts } = this.props
		// 请求actions 发送请求获取数据
		loadProducts()
	}

	render() {
		const { products, addProductToCart } = this.props
		return (
			<section className="container content-section">
				<h2 className="section-header">商品列表</h2>
				<div className="shop-items">
					{products.map((product) => {
						return (
							<div key={product.id} className="shop-item">
								<img
									className="shop-item-image"
									src={`http://localhost:3005${product.thumbnail}`}
								/>
								<span className="shop-item-title">
									{products.title}
								</span>
								<div className="shop-item-details">
									<span className="shop-item-price">
										￥{product.price}
									</span>
									<button
										className="btn btn-primary shop-item-button"
										type="button"
										onClick={() =>
											addProductToCart(product.id)
										}
									>
										加入购物车
									</button>
								</div>
							</div>
						)
					})}
				</div>
			</section>
		)
	}
}
//声明一个函数给connect做第一个参数 把 state 数据放到 props 中
const mapStateToProps = (stata) => ({
	products: stata.products,
})
////声明一个函数给connect做第二个参数 让组件可以通过props使用actions函数
const mapDispatchToProps = (dispatch) => ({
	// 这个方法返回一个对象，结构出来给mapDispatchToProps
	...bindActionCreators(productActions, dispatch),
	...bindActionCreators(cartActions, dispatch),
})

export default connect(mapStateToProps, mapDispatchToProps)(Product)
